//
//  MYGDownloadManager.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/8.
//

import UIKit
class MYGDownloadManager: NSObject {
    static let shared = MYGDownloadManager()
    static let downloadUploadView: MYGUploadDownloadView = {
        let control = MYGUploadDownloadView.init(frame: UIScreen.main.bounds)
        return control
    }()
    
    var downlodingArray = [CXDownloadModel]()//下载中
    var downlodedArray = [CXDownloadModel]()//下载完成
    let dispatchGroup = DispatchGroup()

    func wannaDownlodModel(url:String,fileName:String) ->CXDownloadModel{
        let model = CXDownloadModel()
        model.fileName = fileName
        model.url = url
        return model
    }
    
    func getCacheData() {
        let cachedModels = CXDownloadDatabaseManager.shared.getAllCacheData()
        for(_,obj)in cachedModels.enumerated() {
            if obj.state == .finish {
                MYGDownloadManager.shared.downlodedArray.append(obj)
            }else {
                MYGDownloadManager.shared.downlodingArray.append(obj)
            }
        }
    }
    //添加单个下载任务
    func addDownloadTask(_ model:MYCloudDiskContentModel) {
        //不能下载已经存在的url
        for(_,obj) in MYGDownloadManager.shared.downlodingArray.enumerated() {
            if obj.url == model.url {
                return
            }
        }
        for(_,obj) in MYGDownloadManager.shared.downlodedArray.enumerated() {
            if obj.url == model.url {
                return
            }
        }
        // 增加索引，准备添加下一个对象
        let obj = self.wannaDownlodModel(url: model.url, fileName: model.name)
        MYGDownloadManager.shared.downlodingArray.append(obj)
        NotificationCenter.default.post(name: Notification.Name("MYGCloudDiskDownloadController_addDownloadTask"), object: nil)
        NotificationCenter.default.post(name: Notification.Name("MYCloudDiskHeaderActionView_reloadRedLB"), object: nil)
    }
    
    //添加多个下载任务
    func addDownloadTasks(_ models:[MYCloudDiskContentModel]){
        for (_,obj) in models.enumerated() {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {[weak self] in
                self?.addDownloadTask(obj)
            })
        }
    }
    
    //更新数据
    func updateDownloadModel(_ model:CXDownloadModel,completion:@escaping (()->())) {
        MYGDownloadManager.shared.downlodingArray = MYGDownloadManager.shared.downlodingArray.filter({ obj in
            return obj.url != model.url
        })
        let result = MYGDownloadManager.shared.downlodingArray.filter { obj in
            return obj.url == model.url
        }
        if result.count == 0 {
            MYGDownloadManager.shared.downlodedArray.append(model)
        }
        
        NotificationCenter.default.post(name: Notification.Name("MYCloudDiskHeaderActionView_reloadRedLB"), object: nil)

        completion()
    }
}
